package com.ronghui.cash.util.limu;


import com.ronghui.cash.util.limu.common.MDUtil;
import com.ronghui.cash.util.limu.common.StringUtils;
import org.apache.http.message.BasicNameValuePair;

import java.util.*;
import java.util.Map.Entry;

public class LimuUtil {

	public static String signConvert(String sign, String key) {

		Map<String, String> paramMap = new HashMap<String, String>();
		String ret = "";
		if (!StringUtils.isEmpty(sign)) {
			String[] arr = sign.split("&");
			for (int i = 0; i < arr.length; i++) {
				String tmp = arr[i];
				if (-1 != tmp.indexOf("=")) {
					paramMap.put(tmp.substring(0, tmp.indexOf("=")), tmp.substring(tmp.indexOf("=") + 1, tmp.length()));
				}

			}
		}
		List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(paramMap.entrySet());
		Collections.sort(list, new Comparator<Entry<String, String>>() {
			public int compare(Entry<String, String> o1, Entry<String, String> o2) {
				int ret = 0;
				ret = o1.getKey().compareTo(o2.getKey());
				if (ret > 0) {
					ret = 1;
				} else {
					ret = -1;
				}
				return ret;
			}
		});

		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> mapping : list) {
			if (!"sign".equals(mapping.getKey())) {
				sb.append(mapping.getKey()).append("=").append(mapping.getValue()).append("&");
			}
		}
		sb.setLength(sb.lastIndexOf("&"));
		sb.append(key);
		ret = MDUtil.SHA1(sb.toString());

		// System.out.println(sb.toString());
		return ret;
	}

	public static String strSplitJoint(List<BasicNameValuePair> reqParam) {
		StringBuffer sb = new StringBuffer();
		int index = 1;
		for (BasicNameValuePair nameValuePair : reqParam) {
			sb.append(nameValuePair.getName() + "=" + nameValuePair.getValue());
			if (reqParam.size() != index) {
				sb.append("&");
			}
			index++;
		}
		return sb.toString();
	}

}
